<template>
  <div class="ui-uploader-wrap">
    <div class="ui-uploader-sorts">
      <span>素材分类</span>
      <div class="ui-select">
        <Select v-model="uploadSort" style="width:200px">
          <Option
            v-for="item in sorts"
            :value="item.id"
            :key="item.id"
          >{{ item.category_name }}</Option>
        </Select>
      </div>
    </div>
    <div class="ui-uploader-sorts">
      <span>图片链接</span>
      <div style="width: 400px; margin-left: 10px;">
        <Input search enter-button="确定" v-model="soureLink" placeholder="填写图片URL或直接上传图片"  @on-search="onAddImage"/>
      </div>
    </div>
    <div class="ui-uploader">
      <Upload
        type="drag"
        :action="uploadUrl"
        :on-success="handleSuccess"
        :before-upload="handleBeforeUpload"
        :show-upload-list="false"
        :headers="uploadHeader"
        :data="uploadData"
        :format="['jpg','jpeg','png']"
        :multiple="multiple"
      >
        <div class="ui-uploader--inner">
          <Icon type="md-cloud-upload" />
          <div class="ui-uploader--label">直接拖拽文件到虚线框内即可上传</div>
          <div class="ui-uploader--tips" v-if="multiple">（一次最多能上传 {{ maxLength }} 张图片，每张图片大小不要超过 2M ）</div>
          <div class="ui-uploader--tips" v-else >（一次上传 1 张图片，每张图片大小不要超过 2M ）</div>
        </div>
      </Upload>
    </div>
    <Spin size="large" fix v-if="loading"></Spin>
  </div>
</template>

<script>
import Setting from '@/setting'
export default {
  name: 'ui-uploader',
  props: {
    sorts: {
      type: Array,
      default() {
        return []
      }
    },
    uploadHeader: {
      type: Object,
      default() {
        return {}
      }
    },
    maxLength: {
      type: Number,
      default: 9
    },
    multiple: {
      type: Boolean,
      default: false
    },
  },
  watch: {},
  data() {
    return {
      uploadSort: -1,
      uploadUrl: `${Setting.apiBaseURL}/file/upload`,
      uploadData: {},
      uploadList: [],
      loading: false,
      soureLink: ''
    }
  },
  computed: {},
  methods: {
    handleSuccess(res, file) {
      this.$emit('on-success', {
        res,
        file,
        cid: this.uploadSort
      })
      this.loading = false
    },
    handleBeforeUpload(file) {
      return this.getImageInfo(file)
    },
    getImageInfo(file) {
      let self = this
      self.loading = true
      return new Promise(function(resolve, reject) {
        let filereader = new FileReader()
        filereader.onload = e => {
          let src = e.target.result
          const image = new Image()
          image.onload = function() {
            self.uploadData = {
              img_width: this.width,
              img_height: this.height,
            }
            self.$nextTick(() => {
              resolve()
            })
          }
          image.onerror = reject
          image.src = src
        }
        filereader.readAsDataURL(file)
      })
    },

    // 添加图片链接
    onAddImage() {
        if (this.soureLink) {
            var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
            if (!reg.test(this.soureLink)) {
                return this.$Message.warning('请输入以http / https开头的地址！');
            }
            this.$emit('on-add-imgurl', {
              img_url: this.soureLink,
              cid: this.uploadSort
            })
        } else {
            this.$Message.warning('请输入链接地址！');
        }
    },

  },
  mounted() {}
}
</script>
<style lang="scss">
.ui-uploader {
  .ivu-upload-select {
    display: block;
  }
  .ivu-icon {
    font-size: 48px;
  }
}
.ui-uploader--label,
.ui-uploader--tips {
  color: #999;
}
.ui-uploader--tips {
  margin-top: 6px;
}
</style>
<style lang="scss" scoped>
.ui-uploader-sorts {
  padding-bottom: 8px;
  display: flex;
  align-items: center;
  .ui-select {
    margin-left: 10px;
  }
}
.ui-uploader--inner {
  border: 1px dashed #d8d8d8;
  color: #6af;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}
</style>
